package org.xiaom.butler.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * HttpServletRequest帮助类
 * 
 * @author XM
 * 
 */
public abstract class Util {
	public static boolean deleteFile(String path){
		File f=new File(path);
		if(f.exists()){
			f.delete();
		}
		f=null;
		return true;
	}
	public static String[] upLoadFile(HttpServletRequest request,
			HttpServletResponse response, String path) throws IOException,
			ServletException {
		File tempPathFile = null;
		List<String> names = new LinkedList<String>();
		try {
			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setSizeThreshold(4096); // 设置缓冲区大小，这里是4kb
			factory.setRepository(tempPathFile);// 设置缓冲区目录
			ServletFileUpload upload = new ServletFileUpload(factory);
			upload.setSizeMax(4194304); // 设置最大文件尺寸，这里是4MB

			List<FileItem> items = upload.parseRequest(request);// 得到所有的文件
			Iterator<FileItem> i = items.iterator();
			while (i.hasNext()) {
				FileItem fi = i.next();
				String[] nameItem = fi.getName().split("\\.");
				if (nameItem.length >= 2) {
					String fileSuffix = nameItem[nameItem.length - 1];
					fileSuffix = System.currentTimeMillis() + "." + fileSuffix;
					File fullFile = new File(fileSuffix);
					File savedFile = new File(path, fileSuffix);
					fi.write(savedFile);
					names.add(fileSuffix);
				}
			}
			System.out.print("upload succeed");
		} catch (Exception e) {
			// 可以跳转出错页面
			e.printStackTrace();
		}
		String[] s = new String[names.size()];
		for (int i = 0; i < names.size(); i++) {
			s[i] = names.get(i);
		}
		return s;
	}

	public static void downLoad(HttpServletRequest request,
			HttpServletResponse response,String path,String outName) throws IOException {
		response.reset();
		response.setContentType("application/x-msdownload; charset=UTF-8");
		File pathsavefile = new File(path);
		String[] nameItem = path.split("\\.");
		String fileName;
		if(isBlank(outName)){
			fileName = "data."+nameItem[nameItem.length-1];
		}else{
			fileName=outName;
		}
		response.reset();
		response.setContentType("APPLICATION/OCTET-STREAM");
		fileName = response.encodeURL(new String(fileName.getBytes(), Standard.ENCODE));// 转码
		response.setHeader("Content-Disposition", "attachment; filename=\""
				+ fileName + "\"");
		ServletOutputStream out = response.getOutputStream();
		InputStream inStream = new FileInputStream(pathsavefile);
		byte[] b = new byte[1024];
		int len;
		while ((len = inStream.read(b)) > 0)
			out.write(b, 0, len);
		response.setStatus(response.SC_OK);
		response.flushBuffer();
		out.close();
		inStream.close();
	}

	/**
	 * @param request
	 * @param name
	 * @param defaultValue
	 *            如果没有此参数，需要返回的默认值
	 * @return
	 */
	public static String getQueryParam(HttpServletRequest request, String name,
			String defaultValue) {
		String rs = request.getParameter(name);
		rs=rs==null?"":rs;
		try {
			new String(rs.getBytes("iso-8859-1"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return isBlank(rs) ? defaultValue : rs;
	}

	/**
	 * 7 string==null || "".equals(string)
	 */
	public static boolean isBlank(String str) {
		return str == null || "".equals(str);
	}

	/**
	 * 转向提示网页
	 */
	public static void redirectToErrorPage(HttpServletRequest request,
			HttpServletResponse response, String msg) {
		try {
			request.getSession().setAttribute("error_message", msg);
			response.sendRedirect(request.getContextPath()+"/error.jsp");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * forward
	 */
	public static void forward(ServletContext context,
			HttpServletRequest request, HttpServletResponse response,
			String path, boolean full) {

		try {
			if (full) {
				context.getRequestDispatcher(path).forward(request, response);
			} else {
				context.getRequestDispatcher(Standard.JSP_PATH_PREFIX + path)
						.forward(request, response);
			}
		} catch (Exception e) {
			e.printStackTrace();
			redirectToErrorPage(request, response, "错误的请求");
		}
	}

	/**
	 * forward
	 */
	public static void redirect(HttpServletRequest request,
			HttpServletResponse response, String path, boolean full) {
		try {
			if (full) {
				response.sendRedirect(Standard.JSP_PATH_PREFIX + path);
			} else {
				response.sendRedirect(path);
			}
		} catch (Exception e) {
			e.printStackTrace();
			redirectToErrorPage(request, response, "错误的请求");
		}
	}
}
